<?php
//Plugin: Auto update games
//Author: Ivan
//This plugin automatically updates the statistics in a specific period

if (!isset($website) ) { header('HTTP/1.1 404 Not Found'); die; }

$PluginEnabled = '0';
//Enable edit plugin options
$PluginOptions = '1';

$MaxUpdateGames = '5';
$UpdateTime = '1';
$DisplayStatsLog = '1';

define('OS_MaxUpdateGames',  $MaxUpdateGames);
define('OS_UpdateGamesTime', $UpdateTime);

define('OS_DisplayStatsLog', $DisplayStatsLog);

if ($PluginEnabled == 1) {

  if ( OS_is_admin() AND OS_PluginEdit() ) {
  
  	$UpdateMaxGames = OS_MaxUpdateGames;
	$UpdateTimeMin = OS_UpdateGamesTime;
	$DSL = OS_DisplayStatsLog;
     if ( isset($_POST["OS_MaxUpdateGames"]) ) {
	 
     $UpdateMaxGames = safeEscape($_POST["OS_MaxUpdateGames"]);
	 $UpdateTimeMin = safeEscape($_POST["OS_UpdateGamesTime"]);
	 
	 $DSL = safeEscape(  $_POST["DisplayStatsLog"]);
	 
	 if ( $UpdateMaxGames>=1000 OR $UpdateMaxGames<=0 ) $UpdateMaxGames = 50;
	 if ( $UpdateTimeMin<=0 ) $UpdateTimeMin = 60;
	 
     write_value_of('$MaxUpdateGames', "$MaxUpdateGames", $UpdateMaxGames , $plugins_dir.basename(__FILE__, '') );
	 write_value_of('$UpdateTime', "$UpdateTime", $UpdateTimeMin , $plugins_dir.basename(__FILE__, '') );
	 write_value_of('$DisplayStatsLog', "$DisplayStatsLog", $DSL , $plugins_dir.basename(__FILE__, '') );
    }
	
    $sel = array();
    
	if ($DSL == 1) $sel[0] = 'selected = "selected"'; else $sel[0]='';
	if ($DSL == 0) $sel[1] = 'selected = "selected"'; else $sel[1]='';
	
	$Option = '
<form action="" method="post" >
  <div>Update max: <input size="2" type="text" value="'.$UpdateMaxGames.'" name="OS_MaxUpdateGames" /> games</div>
  <div>Every: <input size="2" type="text" value="'.$UpdateTimeMin.'" name="OS_UpdateGamesTime" /> min.</div>
  
  <div>Display stats log (for admins): 
  <select name="DisplayStatsLog">
    <option '.$sel[0].' value="1">Yes</option>
	<option '.$sel[1].' value="0">No</option>
  </select>
  </div>
  
  <input type="submit" value = "Save" class="menuButtons" />
  <a href="'.OS_HOME.'adm/?plugins" class="menuButtons">Cancel</a>
</form>';

  }
  
    AddEvent("os_content",  "OS_CheckGamesForUpdate"); 
    
	function OS_CheckGamesForUpdate() {
	
	  global $db;
	  global $MinDuration;
	  
	  global $ScoreStart;
	  global $ScoreWins;
	  global $ScoreLosses;
	  
	  $return = "";
	  
	$result = $db->query( "SELECT COUNT(*) FROM ".OSDB_GAMES." 
	WHERE LOWER(map) LIKE LOWER('%dota%') AND stats = 0 AND duration>='".OS_MIN_GAME_DURATION."'" );
    $r = $db->fetch_row($result);
    $TotalGamesForUpdate = $r[0];
	
	$LastUpdateTime = OS_get_custom_field( 0, "last_update_stats" );
	$CurrentTime = time();
	
	if ( ($LastUpdateTime+ (OS_UpdateGamesTime*60) ) <= $CurrentTime ) $UpdateStats = 1; else $UpdateStats = 0;
	
	if ($TotalGamesForUpdate >=1 AND $UpdateStats == 1) {
	
	//GET ALL ADMINS (in array)
	$result = $db->query("SELECT * FROM ".OSDB_ADMINS." WHERE id>=1");
	$admins = array();
	while ($row = $db->fetch_array($result,'assoc')) { $admins[]= strtolower($row["name"]);  }
	//GET ALL USERS FROM SAFELIST
	$result = $db->query("SELECT * FROM ".OSDB_SAFELIST." WHERE id>=1");
	$safelist = array();
	while ($row = $db->fetch_array($result,'assoc')) { $safelist[]= strtolower($row["name"]);	}
	   
	$_result = $db->query( "SELECT id FROM ".OSDB_GAMES." 
	WHERE LOWER(map) LIKE LOWER('%dota%') AND stats = 0 AND duration>='".OS_MIN_GAME_DURATION."' LIMIT ".OS_MaxUpdateGames." " );
	

	 while ($row = $db->fetch_array($_result,'assoc')) {
	 $gid = $row["id"];
	 $result = $db->query("SELECT winner, dp.gameid, gp.colour, newcolour, kills, deaths, assists, creepkills, creepdenies, neutralkills, towerkills, gold,  raxkills, courierkills, g.duration as duration, 
	   gp.name as name, 
	   gp.ip as ip,
	   b.name as banname, b.expiredate, b.warn
	   FROM ".OSDB_DP." AS dp 
	   LEFT JOIN ".OSDB_GP." AS gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	   LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid 
	   LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	   LEFT JOIN ".OSDB_BANS." as b ON b.name=gp.name
	   WHERE dp.gameid='".$gid."'
	   GROUP by gp.name
	   ORDER BY newcolour");
	   
	   if ($db->num_rows($result) <=0)  $update = $db->query("UPDATE ".OSDB_GAMES." SET stats = 1 WHERE id = $gid ;");

	   while ($list = $db->fetch_array($result,'assoc')) {
		
		$kills=$list["kills"];
		$deaths=$list["deaths"];
		$assists=$list["assists"];
		$creepkills=$list["creepkills"];
		$creepdenies=$list["creepdenies"];
		$neutralkills=$list["neutralkills"];
		$towerkills=$list["towerkills"];
		$raxkills=$list["raxkills"];
		$courierkills=$list["courierkills"];
		$duration=$list["duration"];
		$name=mysql_real_escape_string(trim($list["name"]));
		$IPaddress = $list["ip"];
		$banname=$list["banname"];
		$win=$list["winner"];
		$newcolour=$list["newcolour"];
		
		$warn_expire = $list["expiredate"];
		$warn = $list["warn"];
		
		if ( empty($warn_expire ) ) $warn_expire  = '0000-00-00 00:00:00'; 
		
		if ( $warn>=1 ) $warn_qry = 'warn = '.$warn.', '; else $warn_qry = "";
				
		if ( in_array( strtolower($name), $admins ) )   $is_admin = 1; else $is_admin = 0;
		if ( in_array( strtolower($name), $safelist ) ) $is_safe = 1;  else $is_safe  = 0;
		
		if ( strtolower($banname)==strtolower($name) ) $BANNED = 1; else $BANNED = 0;
		
		if ($win==1 AND $newcolour<=5) {$winner = 1; $loser = 0;}
		if ($win==0) {$winner = 0; $loser = 0;}
		if ($win==2 AND $newcolour>5) {$winner = 1; $loser = 0;}
		if ($win==1 AND $newcolour>5) {$winner = 0; $loser = 1;}
		if ($win==2 AND $newcolour<=5) {$winner = 0; $loser = 1;}
		
		if ($winner == 1) $score = $ScoreStart + $ScoreWins;
		if ($winner == 0) $score = $ScoreStart - $ScoreLosses;
		if ($win==0) $score = $ScoreStart;
		
		// Score formula for each game (uncomment below to user score formula)
		// $scoreFormula = (((($kills-$deaths+$assists*0.5+$towerkills*0.5+$raxkills*0.2+($courierkills+$creepdenies)*0.1+$neutralkills*0.03+$creepkills*0.03) * .2)+($score)));
		
		// $score = $scoreFormula;
		
		if ($win==0) $draw = 1; else $draw = 0;
		if (!empty($name) AND $duration >= OS_MIN_GAME_DURATION) {
		$result2 = $db->query("SELECT player FROM ".OSDB_STATS." WHERE LOWER(player) = LOWER('$name')");
		//Create a new player...
		  if ( $db->num_rows($result2) <=0) {
          $sql3 = "INSERT INTO ".OSDB_STATS."(player, score, games, wins, losses, draw, kills, deaths, assists, creeps, denies, neutrals, towers, rax, banned, ip, warn_expire, warn, admin, safelist) 
		  VALUES('$name',$score,1,$winner,$loser,$draw,$kills,$deaths,$assists,$creepkills,$creepdenies,$neutralkills, $towerkills, $raxkills, $BANNED, '$IPaddress', '$warn_expire', '$warn', '$is_admin', '$is_safe')";
          } else {
		  //...or update player data
		  if ($winner == 1) $score = "score = score + $ScoreWins,";
		  if ($winner == 0) $score = "score = score - $ScoreLosses,";
		  if ($win==0) $score = "";
		  $sql3 = "UPDATE ".OSDB_STATS." SET 
		  $score
		  player = '$name',
		  games = games+1, 
		  wins = wins +$winner,
		  losses = losses+$loser,
		  draw = draw + $draw,
		  kills = kills + $kills,
		  deaths = deaths + $deaths,
		  assists = assists + $assists,
		  creeps = creeps + $creepkills,
		  denies = denies + $creepdenies,
		  neutrals = neutrals + $neutralkills,
		  towers = towers + $towerkills,
		  rax = rax + $raxkills,
          banned = $BANNED,
		  ip = '$IPaddress',
		  warn_expire = '$warn_expire',
		  $warn_qry
		  admin = '$is_admin',
		  safelist = '$is_safe'
		  WHERE LOWER(player) = LOWER('$name');";
		   }
		  $result3 = $db->query($sql3);
		 }
		 //$return.="\nGame ($gid) updated!";
	     //Update "games" table so we can know what games have been updated
	     $update = $db->query("UPDATE ".OSDB_GAMES." SET stats = 1 WHERE id = $gid ;");
		 OS_add_custom_field(0, "last_update_stats" ,  time() );
		 
	   }
	   $return.="\nGame ($gid) updated!";
	  }
	  $TotalGamesForUpdate = $TotalGamesForUpdate-OS_MaxUpdateGames;
	  $LastUpdateTime = OS_get_custom_field( 0, "last_update_stats" );
	
	}
	//
	if ( OS_is_admin() AND OS_DisplayStatsLog == 1 AND !$_GET ) {
	?>
<div class="clr"></div>
 <div class="ct-wrapper">
  <div class="outer-wrapper">
   <div class="content section">
    <div class="widget Blog">
     <div class="blog-posts hfeed padLeft padTop padBottom">
	    <h2>Autoupdate stats log</h2>
		
	    <div><b>Remaining games to update:</b> <?=$TotalGamesForUpdate?></div>
		<?php if ($TotalGamesForUpdate>=1) { ?>
		<div><b>Updating max:</b> <?=OS_MaxUpdateGames?> games</div>
		<?php } else { ?>
		<div>All statistics are updated successfully</div>
		<?php } ?>
		
		<div><b>Last update:</b> <?=date("d.m.Y, H:i:s", $LastUpdateTime)?></div>
		<div><b>Next update:</b> <?=date("d.m.Y, H:i:s", ($LastUpdateTime+OS_UpdateGamesTime*60) )?></div>
	 </div>
    </div>
   </div>
  </div>
</div>
	<?php
	}
	
	}
}

?>